package com.dtu.XMLExtras;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class WriteXML {

	public void createXMLfile(String thumbnailPath){

		try{

			DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

			//root elements
			Document doc = docBuilder.newDocument();
			Element rootElement = doc.createElement("Images");
			doc.appendChild(rootElement);

			//staff elements
			Element staff = doc.createElement("Image");
			rootElement.appendChild(staff);

			Element owner = doc.createElement("Owner");
			owner.appendChild(doc.createTextNode("Hilmar Thor Birgisson"));
			staff.appendChild(owner);

			Element tag = doc.createElement("Tag");
			tag.appendChild(doc.createTextNode("Test Tag"));
			staff.appendChild(tag);

			Element thumbnail = doc.createElement("ThumbnailWebAddress");
			thumbnail.appendChild(doc.createTextNode("http://loftur.com/"+thumbnailPath));
			staff.appendChild(thumbnail);


			//write the content into xml file
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			DOMSource source = new DOMSource(doc);
			StreamResult result =  new StreamResult(new File("/mnt/sdcard/DCIM/100MEDIA/test.xml"));
			transformer.transform(source, result);

			System.out.println("Done");

		}catch(ParserConfigurationException pce){
			pce.printStackTrace();
		}catch(TransformerException tfe){
			tfe.printStackTrace();
		}
	} 
}